# -*- coding: utf-8 -*-

'a server example which send hello to client.'

import time, socket, threading, struct, os, requests, pytz, datetime, json, traceback
from datetime import datetime


def get_packet(res):
    '''
    data = {
        "datetime": datetime.now(timezone.utc).astimezone().isoformat()
    }
    '''

    arr = res[1:100]

    def convert_tem(x):
        if x == 255:
            return None
        else:
            return round((x - 90 - 32) / 1.8, 1)

    def convert_tem2(x):
        if x == 32767:
            return None
        else:
            return (x / 10 - 32) / 1.8

    def byte2int(b):
        if not b:
            return 0
        n = b[-1] & 0x7f
        i = len(b)
        j = -1
        while i > 1:
            j = j - 1
            i = i - 1
            n = n * 256 + b[j]
        if b[-1] & 0x80:
            bits = 8 * len(b)
            offset = 2 ** (bits - 1)
            return n - offset
        else:
            return n
        # if not b:  
        #     return 0
        # n = b[0] & 0x7f  
        # for by in b[1:]:
        #     n = n * 256 + by
        # if b[0] & 0x80:  
        #     bits = 8*len(b)
        #     offset = 2**(bits-1)
        #     return n - offset
        # else:
        #     return n

    if res[0] == 6:
        data = {}
        # data['Bar Trend'] = int(arr[3])
        # data['Packet Type'] = int(arr[4])
        # data['Next Record'] = byte2int(arr[5:7])

        data['barometer'] = byte2int(arr[7:9]) / 1000.0 * 33.8638816
        print(data['barometer'])
        # 1英寸汞柱(in Hg)=33.8638816百帕(hpa)
        data['tempIn'] = (byte2int(arr[9:11]) / 10 - 32) / 1.8
        data['rhumIn'] = int(arr[11])
        data['tempOut'] = convert_tem2(byte2int(arr[12:14]))
        data['wind'] = int(arr[14]) * 0.44704
        # It is a byte unsigned value in mph. 1英里/时(mile/h)=0.44704米/秒(m/s)
        data['winAve'] = int(arr[15]) * 0.44704
        data['windDirc'] = byte2int(arr[16:18])

        for index, extra in enumerate(map(convert_tem, list(arr[18:25]))):
            data['tempExtra%d' % (index + 1)] = extra

        # data['Soil Temperatures'] = list(map(convert_tem, list(arr[25:29])))
        for index, extra in enumerate(map(convert_tem, list(arr[25:29]))):
            data['soilTemp%d' % (index + 1)] = extra

        # data['Leaf Temperatures'] = list(map(convert_tem, list(arr[29:33])))
        for index, extra in enumerate(map(convert_tem, list(arr[29:33]))):
            data['leafTemp%d' % (index + 1)] = extra

        data['rhumOut'] = int(arr[33])
        # data['Extra Humidties'] = list(map(convert_tem, list(arr[34:41])))
        for index, extra in enumerate(map(convert_tem, list(arr[34:41]))):
            data['rhumExtra%d' % (index + 1)] = extra

        data['rainRate'] = byte2int(arr[41:43]) * 0.2
        data['uv'] = int(arr[43])  # The unit is in UV index.
        data['solarRadia'] = byte2int(arr[44:46])  # The unit is in watt/meter2
        # data['Storm Rain'] = byte2int(arr[46:48])  # The storm is stored as 100th of an inch
        # data['Start Date of current Storm'] = byte2int(arr[48:50])
        data['rainDay'] = byte2int(arr[50:52]) * 0.2
        data['rainMonth'] = byte2int(arr[52:54]) * 0.2
        data['rainYear'] = byte2int(arr[54:56]) * 0.2
        data['Soil Moistures'] = list(arr[62:66])
        for index, extra in enumerate(map(convert_tem, list(arr[62:66]))):
            data['soilMoinst%d' % (index + 1)] = extra

        # data['Leaf Wetnesses'] = list(arr[66:70])
        for index, extra in enumerate(map(convert_tem, list(arr[66:70]))):
            data['leafWet%d' % (index + 1)] = extra

        data['consoleBatteryV'] = ((byte2int(arr[87:89]) * 300) / 512) / 100.0
        return data


def sendDataToAWIT(data):
    url = 'http://192.168.1.102:8080/GuiYang_weather_BS/push.do?pushStation&username=admin&password=123456'
    # s = json.dumps({'key1': 'value1', 'key2': 'value2'})
    r = requests.post(url, data=data)
    print("服务器反馈信息：")
    print(r.text)


def tcplink(sock, addr):
    print 'Accept new connection from %s:%s...' % addr
    sock.send('Welcome!')
    tel_num = ''
    try:
        while True:
            data = sock.recv(1024)
            if data == 'exit' or not data:
                break
            utc_tz = pytz.timezone('Asia/Chongqing')
            datetimes = datetime.now(tz=utc_tz).isoformat()
            length = len(data)
            w = struct.unpack("B" * length, data)
            time.sleep(1)
            a = {}
            # 判断条件变量，用于修改
            num_len = 11
            if (length == num_len):
                tel_num = data[:11]
            elif (length == 233):
                a = get_packet(w)
                id = {}
                id["datetime"] = datetimes
                id["autoStationId"] = tel_num
                if not a is None:
                    a["ice"] = data[100:]
                    a["id"] = id
            else:
                print("DATA LENGTH ERROR!")

            if data == 'exit' or not data:
                break
            # sock.send('Hello, %s!' % data)

            file_name = tel_num
            print(file_name)
            # 是否有这个路径
            if not os.path.exists(file_path):
                # 创建路径
                os.makedirs(file_path)
            # print(file_suffix)
            # 拼接文件名（包含路径）
            filename = '{}/{}.{}'.format(file_path, file_name, 'txt')
            # otherfile = '{}/{}.{}'.format(file_path,"abandon",'txt')
            print(filename)
            # sock.send('Hello, %s!' % data)
            # sock.send(data)
            # print("send data:")
            # if a:
            # sendDataToAWIT(json.dumps(a))
            # print(str(a))
            if not filename or filename.strip() == '':
                filename = "abandon"
            with open(filename, 'a') as f:
                if a:
                    f.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ':' + str(a) + '\n')
    except:
        traceback.print_exc(file=open(os.path.join(file_path, 'sockserver.log'), 'ab'))
        sock.close()
        print 'Connection from %s:%s closed.' % addr


file_path = '/usr/local/tomcat7/webapps/ROOT/logs/'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('0.0.0.0', 9999))
s.listen(5)
print 'Waiting for connection...'
while True:
    sock, addr = s.accept()

    t = threading.Thread(target=tcplink, args=(sock, addr))
    t.start()
